package cn.tedu.egarticle0811.controller;

import cn.tedu.egarticle0811.base.response.JsonResult;
import cn.tedu.egarticle0811.base.response.StatusCode;
import cn.tedu.egarticle0811.mapper.UserMapper;
import cn.tedu.egarticle0811.pojo.dto.UserArticleParam;
import cn.tedu.egarticle0811.pojo.dto.UserLoginParam;
import cn.tedu.egarticle0811.pojo.entity.Article;
import cn.tedu.egarticle0811.pojo.vo.ArticleVO;
import cn.tedu.egarticle0811.pojo.vo.UserVO;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Slf4j
@Validated
@RestController
@RequestMapping("/v1/user/")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("login")
    public JsonResult userLogin(@RequestBody @Validated UserLoginParam userLoginParam, HttpSession session){
        log.debug("userLoginParam="+ userLoginParam);
        UserVO userVO = userMapper.selectUser(userLoginParam);
        if (userVO == null) {
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        session.setAttribute("user", userVO);
        return JsonResult.ok();
    }

    @PostMapping("article")
    public JsonResult addArticle(@RequestBody @Validated UserArticleParam userArticleParam, HttpSession session) {
        log.debug("userArticleParam="+ userArticleParam);
        UserVO userVO = (UserVO) session.getAttribute("user");
        Article article = new Article();
        BeanUtils.copyProperties(userArticleParam, article);
        article.setUserId(userVO.getId());
        int rows = userMapper.insertArticle(article);
        return JsonResult.ok();
    }

    @GetMapping("selectByArticleId")
    public JsonResult selectByArticleId(@Range(min = 1,max = 100, message = "编号在1~100之间")  Long id) {
        log.debug("id="+id);
        ArticleVO articleVO = userMapper.selectByArticleId(id);
        return JsonResult.ok(articleVO);
    }




























}
